"use client"

import { useState, useEffect } from 'react'

interface QuickRecognitionGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface Question {
  character: string
  options: string[]
  correctAnswer: string
}

export function QuickRecognitionGame({ targetChar, onGameEnd }: QuickRecognitionGameProps) {
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
  const [selectedAnswer, setSelectedAnswer] = useState<string>('')
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [level, setLevel] = useState(1)
  const [gameStarted, setGameStarted] = useState(false)
  const [correctCount, setCorrectCount] = useState(0)
  const [totalQuestions, setTotalQuestions] = useState(0)
  const [showResult, setShowResult] = useState(false)

  // 题目库
  const questions: Question[] = [
    { character: '目', options: ['tú', 'yè', 'pí', 'mù'], correctAnswer: 'mù' },
    { character: '木', options: ['mù', 'tǔ', 'shuǐ', 'huǒ'], correctAnswer: 'mù' },
    { character: '水', options: ['shuǐ', 'huǒ', 'tǔ', 'mù'], correctAnswer: 'shuǐ' },
    { character: '火', options: ['huǒ', 'shuǐ', 'tǔ', 'mù'], correctAnswer: 'huǒ' },
    { character: '土', options: ['tǔ', 'shuǐ', 'huǒ', 'mù'], correctAnswer: 'tǔ' },
    { character: '人', options: ['rén', 'dà', 'xiǎo', 'shān'], correctAnswer: 'rén' },
    { character: '大', options: ['dà', 'xiǎo', 'rén', 'shān'], correctAnswer: 'dà' },
    { character: '小', options: ['xiǎo', 'dà', 'rén', 'shān'], correctAnswer: 'xiǎo' }
  ]

  // 初始化游戏
  useEffect(() => {
    generateNewQuestion()
  }, [])

  // 计时器
  useEffect(() => {
    if (gameStarted && timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      onGameEnd(score, correctCount, totalQuestions)
    }
  }, [timeLeft, gameStarted, score, correctCount, totalQuestions, onGameEnd])

  const generateNewQuestion = () => {
    const randomQuestion = questions[Math.floor(Math.random() * questions.length)]
    setCurrentQuestion(randomQuestion)
    setSelectedAnswer('')
    setShowResult(false)
  }

  const handleAnswerClick = (answer: string) => {
    if (!gameStarted) setGameStarted(true)
    if (selectedAnswer) return // 已经选择过答案

    setSelectedAnswer(answer)
    setTotalQuestions(prev => prev + 1)
    setShowResult(true)

    if (answer === currentQuestion?.correctAnswer) {
      setScore(prev => prev + 100)
      setCorrectCount(prev => prev + 1)
    }

    // 2秒后显示下一题
    setTimeout(() => {
      generateNewQuestion()
    }, 2000)
  }

  const resetGame = () => {
    setScore(0)
    setTimeLeft(60)
    setGameStarted(false)
    setCorrectCount(0)
    setTotalQuestions(0)
    generateNewQuestion()
  }

  if (!currentQuestion) return null

  return (
    <div className="h-full flex flex-col bg-white rounded-2xl p-6 relative">
      {/* 游戏标题和关闭按钮 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-orange-500 rounded-lg flex items-center justify-center">
            <span className="text-white text-lg">⚡</span>
          </div>
          <h3 className="text-xl font-bold text-gray-800">快速识字挑战</h3>
        </div>
        <button
          onClick={() => onGameEnd(score, correctCount, totalQuestions)}
          className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white hover:bg-red-600 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* 游戏状态栏 */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{score}</div>
          <div className="text-sm text-gray-600">得分</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">
            {Math.floor(timeLeft / 60).toString().padStart(2, '0')}:
            {(timeLeft % 60).toString().padStart(2, '0')}
          </div>
          <div className="text-sm text-gray-600">时间</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{level}</div>
          <div className="text-sm text-gray-600">关卡</div>
        </div>
      </div>
      
      {/* 游戏区域 */}
      <div className="flex-1 flex flex-col items-center justify-center space-y-8">
        {/* 汉字显示 */}
        <div className="text-center">
          <div className="w-32 h-32 bg-gray-800 rounded-2xl flex items-center justify-center mb-4">
            <span className="text-6xl font-bold text-white">
              {currentQuestion.character}
            </span>
          </div>
          {showResult && (
            <div className={`text-lg font-bold ${
              selectedAnswer === currentQuestion.correctAnswer ? 'text-green-600' : 'text-red-600'
            }`}>
              {selectedAnswer === currentQuestion.correctAnswer ? '✅ 正确！' : '❌ 错误！'}
            </div>
          )}
        </div>

        {/* 选项按钮 */}
        <div className="grid grid-cols-2 gap-4 max-w-md">
          {currentQuestion.options.map((option, index) => (
            <button
              key={index}
              onClick={() => handleAnswerClick(option)}
              disabled={!!selectedAnswer}
              className={`
                px-8 py-4 rounded-2xl text-lg font-bold transition-all duration-300
                ${selectedAnswer
                  ? option === currentQuestion.correctAnswer
                    ? 'bg-green-500 text-white'
                    : option === selectedAnswer
                    ? 'bg-red-500 text-white'
                    : 'bg-gray-300 text-gray-500'
                  : 'bg-gray-100 text-gray-800 hover:bg-gray-200 hover:scale-105'
                }
                ${selectedAnswer ? 'cursor-not-allowed' : 'cursor-pointer'}
              `}
            >
              {option}
            </button>
          ))}
        </div>
      </div>

      {/* 底部控制按钮 */}
      <div className="flex justify-center space-x-4 mt-6">
        <button 
          onClick={() => setGameStarted(!gameStarted)}
          className="px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2"
        >
          <span>{gameStarted ? '⏸️' : '▶️'}</span>
          <span>{gameStarted ? '暂停' : '开始'}</span>
        </button>
        <button 
          onClick={resetGame}
          className="px-6 py-2 bg-orange-500 text-white rounded-full hover:bg-orange-600 transition-colors flex items-center space-x-2"
        >
          <span>🔄</span>
          <span>重新开始</span>
        </button>
        <button className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center space-x-2">
          <span>⏭️</span>
          <span>下一关</span>
        </button>
        <button 
          onClick={() => onGameEnd(score, correctCount, totalQuestions)}
          className="px-6 py-2 bg-gray-500 text-white rounded-full hover:bg-gray-600 transition-colors flex items-center space-x-2"
        >
          <span>🚪</span>
          <span>退出游戏</span>
        </button>
      </div>
    </div>
  )
} 